package com.shortchina.controller;

import com.shortchina.common.CommonCache;
import com.shortchina.config.redis.RedisService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 短链接控制器
 *
 * @author fc
 * @version 1.0
 * @data 2024/12/23 11:38 下午
 **/
@RestController
public class UController {
    @Value("${tshort.white_list:null}")
    private String whiteList;
    @Resource
    private RedisService redisService;

    @GetMapping("/s/{shortUrl}")
    public void u(HttpServletResponse response, @PathVariable String shortUrl) throws IOException {

        //访问统计
        redisService.zIncrementScore(CommonCache.ACCESS_COUNT, shortUrl);
        //302跳转
        if (StringUtils.isNotBlank(shortUrl)) {
            String url = redisService.get(CommonCache.SHORT_URL + shortUrl);
            String[] bmds = whiteList.split(",");
            //白名单判定
            try {
                URL url1 = new URL(url);
                String domain = url1.getHost();
                for (String bmd : bmds) {
                    if (bmd.startsWith(domain)) {
                        break;
                    }else{
                        response.setContentType("text/html;charset=UTF-8");
                        response.setCharacterEncoding("UTF-8");
                        response.getWriter().write("<H1>不在白名单内</H1>");
                        return;
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            if (StringUtils.isNotBlank(url)) {
                if (!(url.startsWith("http://") || url.startsWith("https://"))) {
                    url = "http://" + url;
                }
                response.sendRedirect(url);
                return;
            }
        }
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("<H1>!短链已失效</H1>");
    }

}

